package com.myk.game.gobangchess.services;

import com.myk.game.gobangchess.Account;
import com.myk.game.gobangchess.DataManager;
import com.myk.game.gobangchess.Manager;
import com.myk.game.gobangchess.Player;
import com.myk.game.gobangchess.constants.AppConfig;
import com.myk.game.gobangchess.constants.Msger;
import com.myk.game.gobangchess.dates.AccountData;
import com.myk.game.gobangchess.utils.DateTimeUtil;
import com.myk.game.gobangchess.utils.StringUtils;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.time.LocalDateTime;

//处理登陆业务
public class LoginService implements Runnable {

    private Socket socket;
    private DataInputStream dis;
    private DataOutputStream dos;

    public LoginService(Socket socket) {
        this.socket = socket;
        try {
            this.dis = new DataInputStream(socket.getInputStream());
            this.dos = new DataOutputStream(socket.getOutputStream());
        }
        catch (IOException e) {
            e.printStackTrace();
            recycle();
        }
    }

    @Override
    public void run() {
        try {
            dos.writeUTF(Msger.createMsg(Msger.connSuccess, "Ok")); //通知客户端链接成功
        }
        catch (Exception e) {
            e.printStackTrace();
            System.out.println("服务器向客户端发送消息失败");
            recycle();
        }
        try {
            String msg = dis.readUTF();
            System.out.println("连接消息：" + msg);
            String msgType = Msger.getMsgType(msg);
            //玩家登陆
            if (msgType.equals(Msger.requestLogin)) {
                String value = Msger.getValueByType(msg, Msger.requestLogin);
                if (value != null) {
                    String idCode = value.split("@")[0];
                    String versionCode = value.split("@")[1];
                    Account account = AccountData.getAccountByIdCode(idCode);
                    if (account != null) {
                        boolean isBan = AccountData.isAccountUnderBan(account);
                        if (!isBan) {
                            if (versionCode != null && versionCode.equals(AppConfig.player_apk_version_name)) {
                                Player hasPlayer = null;
                                for (Player player : DataManager.playerList) {
                                    if (player.getIdCode().equals(account.getIdCode())) {
                                        hasPlayer = player;
                                    }
                                }
                                if (hasPlayer == null) {
                                    Player newPlayer = new Player(socket.getInetAddress().toString(), socket, dos, dis, account); //创建玩家
                                    DataManager.playerLogin(newPlayer); //添加新的玩家，新玩家初始化，知其它玩家
                                }
                                else {
                                    System.out.println("玩家已在线");
                                    System.out.println(socket.getInetAddress().toString() + "和" + hasPlayer.getRecentIp());
                                /*if (socket.getInetAddress().toString().equals(hasPlayer.getRecentIp())) { //判断是否相同的网段来防止顶号
                                    hasPlayer.reConnect(socket, dos, dis, account); //重新连接
                                }
                                else {
                                    dos.writeUTF(Msger.createMsg(Msger.loginFailed, "玩家已在线"));
                                    recycle();
                                }*/
                                    //用wifi和流量的用户总是会自动切换ip实在影响体验就不校验ip了，这样就不能防止别人顶你号了
                                    hasPlayer.reConnect(socket, dos, dis, account); //重新连接
                                }
                            }
                            else {
                                dos.writeUTF(Msger.createMsg(Msger.updateVersion, DataManager.getPlayerApkVersion()));
                                dos.writeUTF(Msger.createMsg(Msger.loginFailed, "版本不一致\n最新版本" + AppConfig.player_apk_version_name + ",\n更新失败请联系" + AppConfig.manager_contact + "。"));
                                System.out.println("版本不一致");
                                recycle();
                            }
                        }
                        else {
                            dos.writeUTF(Msger.createMsg(Msger.loginFailed, "该账号审核被拒绝\n请联系管理员" + AppConfig.manager_contact));
                            recycle();
                        }
                    }
                    else {
                        dos.writeUTF(Msger.createMsg(Msger.loginFailed, "账号不存在\n请联系管理员" + AppConfig.manager_contact));
                        recycle();
                    }
                }
                else {
                    dos.writeUTF(Msger.createMsg(Msger.loginFailed, "消息格式不正确\n请联系管理员" + AppConfig.manager_contact));
                    System.out.println("登录消息格式不正确");
                    recycle();
                }
            }
            //玩家注册
            else if (msgType.equals(Msger.requestRegister)) {
                String value = Msger.getValueByType(msg, Msger.requestRegister);
                if (value != null) {
                    String versionCode = value.split("&")[3];
                    if (versionCode != null && versionCode.equals(AppConfig.player_apk_version_name)) {
                        int registerCount = AccountData.getRegisterCount(); //获取当前新注册未审核的账号数量
                        if (registerCount < Integer.parseInt(AppConfig.register_max_count)) {
                            String idCode = value.split("&")[0];
                            boolean isIdCodeExit = AccountData.isIdCodeAccess(idCode);
                            if (!isIdCodeExit) {
                                String nickName = value.split("&")[1];
                                if (StringUtils.isMatch(nickName)) {
                                    String contact = value.split("&")[2];
                                    boolean isNickNameExit = AccountData.isNicknameAccess(nickName);
                                    if (!isNickNameExit) { //昵称已存在
                                        String createTime = DateTimeUtil.localDateTimeToStr(LocalDateTime.now(), DateTimeUtil.DATE_FORMAT);
                                        if (AccountData.managerCreateAccount(idCode, nickName, createTime)) {  //创建账户文件夹
                                            String tempNickName = AccountData.generateTempNickName();
                                            AccountData.setAccountUnderCheck(idCode, nickName, tempNickName); //设置账号为审核状态，插入标记文件并保存临时昵称
                                            AccountData.updatePlayerContact(idCode, nickName, contact); //保存联系方式
                                            String successTipMsg = idCode + "&" + "账号已缓存：" + idCode + "\n临时昵称为：" + tempNickName + "\n\n(您还可以联系管理员" + AppConfig.manager_contact + "加速审核。)";
                                            dos.writeUTF(Msger.createMsg(Msger.registerSuccess, successTipMsg));
                                            System.out.println("账号：" + idCode + "," + nickName + "," + tempNickName + "注册成功");
                                        }
                                        else {
                                            dos.writeUTF(Msger.createMsg(Msger.registerFailed, "账户数据生成失败\n请联系管理员"));
                                            recycle();
                                        }
                                    }
                                    else {
                                        dos.writeUTF(Msger.createMsg(Msger.registerFailed, "该昵称已被使用"));
                                        recycle();
                                    }
                                }
                                else {
                                    dos.writeUTF(Msger.createMsg(Msger.registerFailed, "昵称格式不符合要求"));
                                    recycle();
                                }
                            }
                            else {
                                dos.writeUTF(Msger.createMsg(Msger.registerFailed, "该账号已被使用"));
                                recycle();
                            }
                        }
                        else {
                            dos.writeUTF(Msger.createMsg(Msger.registerFailed, "今日自主注册名额已满\n可联系管理员" + AppConfig.manager_contact));
                            System.out.println("注册人数已满");
                            recycle();
                        }
                    }
                    else {
                        dos.writeUTF(Msger.createMsg(Msger.updateVersion, DataManager.getPlayerApkVersion()));
                        dos.writeUTF(Msger.createMsg(Msger.loginFailed, "版本不一致\n最新版本" + AppConfig.player_apk_version_name + ",\n更新失败请联系" + AppConfig.manager_contact + "。"));
                        recycle();
                    }
                }
                else {
                    dos.writeUTF(Msger.createMsg(Msger.registerFailed, "消息格式不正确"));
                    System.out.println("注册消息格式不正确");
                    recycle();
                }
            }
            //管理员登陆
            else if (msgType.equals(Msger.requestManagerLogin)) {
                String value = Msger.getValueByType(msg, Msger.requestManagerLogin);
                if (value != null) {
                    String idCode = value.split("@")[0];
                    String versionCode = value.split("@")[1];
                    if (DataManager.checkManager(idCode)) {
                        if (versionCode != null && versionCode.equals(AppConfig.manager_apk_version)) {
                            if (DataManager.manager == null) {
                                Manager manager = new Manager(socket, dos, dis); //创建管理员
                                DataManager.managerLogin(manager); //管理员登录
                            }
                            else {
                                if (DataManager.manager.isTimeOut()) {
                                    System.out.println("旧管理员超时，新管理员顶替");
                                    Manager manager = new Manager(socket, dos, dis); //创建管理员
                                    DataManager.managerLogin(manager); //管理员登录
                                }
                                else {
                                    System.out.println("管理员已在线");
                                    dos.writeUTF(Msger.createMsg(Msger.managerLoginFailed, "管理员已在线"));
                                    recycle();
                                }
                            }
                        }
                        else {
                            dos.writeUTF(Msger.createMsg(Msger.managerLoginFailed, "当前版本已不可使用"));
                            System.out.println("管理员应用本版不一致");
                            recycle();
                        }
                    }
                    else {
                        dos.writeUTF(Msger.createMsg(Msger.managerLoginFailed, "账号错误"));
                        System.out.println("管理员登录账号错误");
                        recycle();
                    }
                }
                else {
                    dos.writeUTF(Msger.createMsg(Msger.managerLoginFailed, "消息格式不正确"));
                    System.out.println("管理员登录消息格式不正确");
                    recycle();
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            recycle(); //登录时异常断开
        }
    }

    //回收资源
    private void recycle() {
        try {
            Thread.sleep(10);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            if (dis != null) {
                this.dis.close();
            }
            if (dos != null) {
                this.dos.close();
            }
            if (socket != null) {
                this.socket.close();
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}